package com.dayi.fragment;

import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.dayi.R;
import com.dayi.R2;
import com.dayi.bean.DayiBean;
import com.dayi.bean.SendMessageToUs;
import com.dayi.bean.ShowActivityBean;
import com.dayi.view.SmartScrollView;
import com.dayi.view.VerticalData;
import com.dayi.view.VerticalScrollView;
import com.lib.app.ARouterPathUtils;
import com.lib.app.CodeUtil;
import com.lib.bean.BannerDescripeBean;
import com.lib.bean.BannerNormal;
import com.lib.bean.CustomData;
import com.lib.fastkit.db.shared_prefrences.SharedPreferenceManager;
import com.lib.fastkit.db.shared_prefrences.interfaces.UserCacheInterface;
import com.lib.fastkit.http.ok.HttpUtils;
import com.lib.fastkit.utils.log.LogUtil;
import com.lib.fastkit.utils.permission.custom.PermissionUtil;
import com.lib.fastkit.utils.time_deal.TimeUtils;
import com.lib.fastkit.views.dialog.zenhui.AlertDialog;
import com.lib.fastkit.views.load_state_view.MultiStateView;
import com.lib.fastkit.views.progress.circle_progress.CircleProgress;
import com.lib.fastkit.views.recyclerview.zhanghongyang.base.ViewHolder;
import com.lib.fastkit.views.spring_refresh.container.DefaultFooter;
import com.lib.fastkit.views.spring_refresh.container.DefaultHeader;
import com.lib.fastkit.views.spring_refresh.widget.SpringView;
import com.lib.framework.component.interceptor.GroupUtils;
import com.lib.http.call_back.HttpNormalCallBack;
import com.lib.ui.adapter.BaseAdapter;
import com.lib.ui.fragment.BaseAppFragment;
import com.lib.utls.glide.GlideConfig;
import com.lib.view.banner.MyBannerNormal;
import com.lib.view.player.MyJzvdStd;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


@Route(path = ARouterPathUtils.Dayi_DayiFragment_1)
public class DayiFragment_1 extends BaseAppFragment {

    @BindView(R2.id.circle_progress_bar2)
    CircleProgress circleProgressBar2;
    @BindView(R2.id.btn_paihang)
    Button btnPaihang;
    @BindView(R2.id.jz_player)
    MyJzvdStd jzPlayer;

    @BindView(R2.id.scroll_dayi1)
    VerticalScrollView scrollDayi1;
    @BindView(R2.id.scroll_dayi2)
    VerticalScrollView scrollDayi2;

    @BindView(R2.id.lin_ask)
    FrameLayout linAsk;

    @BindView(R2.id.tv_pagerTest)
    TextView tvPagerTest;
    @BindView(R2.id.tv_difficult)
    TextView tvDifficult;
    @BindView(R2.id.tv_fun)
    TextView tvFun;
    @BindView(R2.id.lin_paperTest)
    LinearLayout linPaperTest;
    @BindView(R2.id.lin_difficult)
    LinearLayout linDifficult;
    @BindView(R2.id.lin_fun)
    LinearLayout linFun;
    @BindView(R2.id.lin_situation)
    LinearLayout linSituation;
    @BindView(R2.id.tv_erronNum)
    TextView tvErronNum;
    @BindView(R2.id.lin_errorBook)
    LinearLayout linErrorBook;

    @BindView(R2.id.lin_search)
    LinearLayout linSearch;
    @BindView(R2.id.tv_share_money)
    TextView tvShareMoney;

    @BindView(R2.id.banner_tuxun)
    MyBannerNormal bannerTuxun;
    @BindView(R2.id.lin_tuXun)
    LinearLayout linTuXun;
    @BindView(R2.id.lin_more1)
    LinearLayout linMore1;

    @BindView(R2.id.tv_bottomline)
    TextView tvBottomline;
    @BindView(R2.id.smartScroll)
    SmartScrollView smartScroll;


    //    @BindView(R2.id.lin_more2)
//    LinearLayout linMore2;
    @BindView(R2.id.springView)
    SpringView springView;
    @BindView(R2.id.state_view)
    MultiStateView stateView;

    List<DayiBean.ObjBean.ArticleRabbitListBean> getArticle_rabbit_list = new ArrayList<>();

    private List<DayiBean.ObjBean.FamousTeacherListBean> mListTeacher = new ArrayList<>();
    private List<BannerNormal> mListClass = new ArrayList<>();
    private List<DayiBean.ObjBean.ArticleRabbitListBean> tuxunContentList = new ArrayList<>();

    //老师列表适配器
    TeacherListAdapter teacherListAdapter;

    @Override
    protected void onCreateView(View view, Bundle savedInstanceState) {
        stateView.setViewState(MultiStateView.VIEW_STATE_LOADING);
        stateView.setMultiStateViewLisener(new MultiStateView.MultiStateViewLisener() {
            @Override
            public void onTryAgain() {
                initData();
            }
        });
        initView();

        isShowActivity();

        initData();

    }

    private void isShowActivity() {

        HttpUtils.with(getActivity())
                .addParam("requestType", "ACTIVITY")
                .execute(new HttpNormalCallBack<ShowActivityBean>() {
                    @Override
                    public void onSuccess(ShowActivityBean result) {

                        //如果状态码等于200，那么将有活动展示
                        if (200 == result.getCode()) {

                            LogUtil.e("---------------服务器返回的key====" + result.getObj().getActivity_key());

                            if ("".equals(SharedPreferenceManager.getInstance(getActivity()).getUserCache().getActivityKey())) {

                                LogUtil.e("-----------------------还没有key");

                                //之前没活动，展示
                                showActivityDialog(result.getObj());

                                //活动code保存下来，方便下次判断
                                UserCacheInterface userCacheInterface = SharedPreferenceManager.getInstance(getActivity()).getUserCache();
                                userCacheInterface.setActivityKey(result.getObj().getActivity_key());

                            } else {
                                String oldCode = SharedPreferenceManager.getInstance(getActivity()).getUserCache().getActivityKey();

                                LogUtil.e("-----------------------老的key=" + oldCode);

                                if (oldCode.equals(result.getObj().getActivity_key())) {

                                    //两次相等，表示活动一样，不展示

                                } else {

                                    //活动code保存下来，方便下次判断
                                    UserCacheInterface userCacheInterface = SharedPreferenceManager.getInstance(getActivity()).getUserCache();
                                    userCacheInterface.setActivityKey(result.getObj().getActivity_key());

                                    showActivityDialog(result.getObj());

                                }
                            }
                        }
                    }

                    @Override
                    public void onError(String e) {


                    }
                });


    }


    private void showActivityDialog(final ShowActivityBean.ObjBean objBean) {

        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_showactivity, null);

        ImageView imageHide = view.findViewById(R.id.iv_hideshow);
        ImageView imageShow = view.findViewById(R.id.iv_showimg);

        Glide.with(getActivity())
                .load(objBean.getActivity_icon())
                .apply(GlideConfig.getRoundOptions(5))
                .into(imageShow);

        final AlertDialog dialog = new AlertDialog.Builder(getActivity())
                .setContentView(view)
                .setCancelable(false)
                .show();

        imageHide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                dialog.dismiss();

            }
        });

        imageShow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (0 == objBean.getActivity_click()) {

                } else if (1 == objBean.getActivity_click()) {

                    ARouter.getInstance().build(ARouterPathUtils.App_NormalDetailWebActivity)
                            .withString("urlPath", objBean.getActivity_link()).navigation();

                }
                dialog.dismiss();

            }
        });

    }

    private void initView() {

        springView.setHeader(new DefaultHeader(getActivity()));
        springView.setFooter(new DefaultFooter(getActivity()));
        springView.setEnableFooter(false);
        springView.setListener(new SpringView.OnFreshListener() {
            @Override
            public void onRefresh() {

                initData();

            }

            @Override
            public void onLoadmore() {
                springView.onFinishFreshAndLoad();
            }
        });

//        teacherListAdapter = new TeacherListAdapter(getActivity(), mListTeacher);
//        LinearLayoutManager manager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
//        recyTeacherlist.setLayoutManager(manager);
//        recyTeacherlist.setAdapter(teacherListAdapter);


        //通过监听滑动的回调设置是否可见
        smartScroll.setScanScrollChangedListener(new SmartScrollView.ISmartScrollChangedListener() {
            @Override
            public void onScrolledToBottom() {
                LogUtil.e("on============ScrolledToBottom");
                tvBottomline.setVisibility(View.VISIBLE);
            }

            @Override
            public void onScrolledToTop() {
                LogUtil.e("on============ScrolledToTop");
                tvBottomline.setVisibility(View.GONE);
            }
        });


    }


    private DayiBean dayiBean;

    private void initData() {

        HttpUtils.with(getContext())
                .addParam("requestType", "RABBIT_PAGE_DATA")
                .execute(new HttpNormalCallBack<DayiBean>() {
                    @Override
                    public void onSuccess(final DayiBean result) {
                        springView.onFinishFreshAndLoad();
                        if (result.getCode() == CodeUtil.CODE_200) {
                            dayiBean = result;

                            /**
                             * 进度条
                             */

                            circleProgressBar2.setValue((int) result.getObj().getGrand_total());

                            /**
                             * 视频
                             */

                            String videoUrl = result.getObj().getQuestion_introduction();

                            if (!"".equals(videoUrl) && jzPlayer != null) {
                                jzPlayer.setUp(videoUrl, "");
                                jzPlayer.startVideo();
                                Glide.with(getActivity()).load(videoUrl).into(jzPlayer.thumbImageView);
                            }

                            /**
                             * 消息列表
                             */
                            List<DayiBean.ObjBean.RecentQuestionBean> getRecent_question = result.getObj().getRecent_question();
//                            initMessageList(getRecent_question);
                            initVerticalData1(getRecent_question);
                            initVerticalData2(getRecent_question);

                            /**
                             * 刷题兔币
                             */
                            tvPagerTest.setText("+ " + result.getObj().getAnswer_difficulty_reward() + "兔币");
                            tvDifficult.setText("+ " + result.getObj().getAnswer_difficulty_reward() + "兔币");
                            tvFun.setText("+ " + result.getObj().getAnswer_interest_reward() + "兔币");

                            //错题数量
                            tvErronNum.setText(result.getObj().getWrong_quantity());
//                            btnAnalysis.setValue(result.getObj().getStudydiagnosis_content_reward());


                            /**
                             * 兔讯-----------banner
                             */
                            if (getArticle_rabbit_list.size() > 0) {
                                getArticle_rabbit_list.clear();
                            }
                            if (mListClass.size() > 0) {
                                mListClass.clear();
                            }
                            getArticle_rabbit_list = result.getObj().getArticle_rabbit_list();
                            iniTuXun(getArticle_rabbit_list);

                            /**
                             * 新闻
                             */
                            List<DayiBean.ObjBean.ArticleListBean> getArticle_list = result.getObj().getArticle_list();
                            initArticle(getArticle_list);


                            /**
                             * 搜索兔币
                             *
                             */
                            tvShareMoney.setText("分享兔讯得" + result.getObj().getArticle_share_reward() + "元现金");

                            /**
                             * 名师专栏
                             */
//                            List<DayiBean.ObjBean.FamousTeacherListBean> getFamous_teacher_list = result.getObj().getFamous_teacher_list();
//                            initTeacherList(getFamous_teacher_list);

                            stateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);


                        } else {
                            stateView.setViewState(MultiStateView.VIEW_STATE_ERROR);
                        }
                    }

                    @Override
                    public void onError(String e) {
                        springView.onFinishFreshAndLoad();

                        if (stateView != null) {
                            stateView.setViewState(MultiStateView.VIEW_STATE_NETWORK_ERROR);
                        }
                    }
                });


    }

    @Override
    public void onResume() {
        super.onResume();

        LogUtil.e("stateView状态的值为：" + stateView.getViewState());
        if (stateView.getViewState() != MultiStateView.VIEW_STATE_CONTENT) {
            initData();
        }

    }


    @Override
    public void onPause() {
        super.onPause();
        jzPlayer.releaseAllVideos();

    }

    @Override
    public void onStop() {
        super.onStop();

    }

    /**
     * 滚动条1
     *
     * @param getRecent_question
     */
    private void initVerticalData1(List<DayiBean.ObjBean.RecentQuestionBean> getRecent_question) {

        List<VerticalData> list = new ArrayList<>();

        for (int i = 0; i < getRecent_question.size(); i++) {
            if (i % 2 == 0) {
                list.add(new VerticalData(getRecent_question.get(i).getIdentity() + "",
                        getRecent_question.get(i).getMsg(), getRecent_question.get(i).getCreate_date()));
            }

        }

        scrollDayi1.setViews(1,list);
    }

    /**
     * 滚动条2
     *
     * @param getRecent_question
     */
    private void initVerticalData2(List<DayiBean.ObjBean.RecentQuestionBean> getRecent_question) {

        List<VerticalData> list = new ArrayList<>();

        for (int i = 0; i < getRecent_question.size(); i++) {
            if (i % 2 == 1) {
                list.add(new VerticalData(getRecent_question.get(i).getIdentity() + "",
                        getRecent_question.get(i).getMsg(), getRecent_question.get(i).getCreate_date()));
            }

        }

        scrollDayi2.setViews(1,list);

    }

    /**
     * 兔讯初始化
     *
     * @param getArticle_rabbit_list
     */
    private void iniTuXun(final List<DayiBean.ObjBean.ArticleRabbitListBean> getArticle_rabbit_list) {

        for (int i = 0; i < getArticle_rabbit_list.size(); i++) {

            BannerNormal bannerNormal = new BannerNormal();

            CustomData customData = new CustomData(getArticle_rabbit_list.get(i).getCover(),
                    getArticle_rabbit_list.get(i).getArtic_link(), "", false);

            BannerDescripeBean descripeBean = new BannerDescripeBean();
            descripeBean.setTitle(getArticle_rabbit_list.get(i).getTitle());
            descripeBean.setSeeNum(getArticle_rabbit_list.get(i).getAccess());
            descripeBean.setDate(getArticle_rabbit_list.get(i).getCreate_date());

            bannerNormal.setCustomData(customData);
            bannerNormal.setDescripeBean(descripeBean);

            mListClass.add(bannerNormal);

        }

        bannerTuxun.setupdateData(mListClass, MyBannerNormal.TYPE_RECTANGULAR);

        bannerTuxun.setMyBannerNormalListener(new MyBannerNormal.MyBannerNormalListener() {
            @Override
            public void onBannerClick(int positon) {

                if (positon < getArticle_rabbit_list.size()) {
                    ARouter.getInstance().build(ARouterPathUtils.App_NormalDetailWebActivity)
                            .withString("urlPath", getArticle_rabbit_list.get(positon).getArtic_link()).navigation();
                }

            }
        });
    }


    /**
     * 文章初始化
     *
     * @param getArticle_list
     */

    private void initArticle(List<DayiBean.ObjBean.ArticleListBean> getArticle_list) {
        linTuXun.removeAllViews();

        for (DayiBean.ObjBean.ArticleListBean articleListBean : getArticle_list) {
            insertArticle(articleListBean);
        }

    }

    private void insertArticle(final DayiBean.ObjBean.ArticleListBean articleListBean) {

        View root = LayoutInflater.from(getContext()).inflate(R.layout.item_tuxun2, null);
        TextView tv_title = root.findViewById(R.id.tv_title);
        TextView tv_watch = root.findViewById(R.id.tv_watch);
        ImageView iv_cover = root.findViewById(R.id.iv_cover);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f);
        lp.gravity = Gravity.CENTER;
        root.setLayoutParams(lp);
        tv_title.setText(articleListBean.getTitle());
        tv_watch.setText(articleListBean.getAccess());
        Glide.with(getContext())
                .load(articleListBean.getCover())
                .apply(GlideConfig.getRoundOptions(20))
                .into(iv_cover);
        linTuXun.addView(root);

        root.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                ARouter.getInstance().build(ARouterPathUtils.App_NormalDetailWebActivity)
                        .withString("urlPath", articleListBean.getArtic_link())
                        .navigation();

            }
        });

    }


    /**
     * 名师专栏初始化
     *
     * @param getFamous_teacher_list
     */
    private void initTeacherList(final List<DayiBean.ObjBean.FamousTeacherListBean> getFamous_teacher_list) {

        mListTeacher.clear();
        mListTeacher.addAll(getFamous_teacher_list);
        teacherListAdapter.updateData(mListTeacher);
        teacherListAdapter.notifyDataSetChanged();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_dayi_1;
    }

    private void goAskQuestion() {

        ARouter.getInstance().build(ARouterPathUtils.Dayi_AskQuestionActivity, GroupUtils.NEED_LOGIN).navigation();

//        PermissionUtil.getInstance(getActivity()).externalAudio(new PermissionUtil.RequestPermission() {
//            @Override
//            public void onRequestPermissionSuccess() {
//            }
//
//            @Override
//            public void onRequestPermissionFailure() {
//
//            }
//        });


    }


    @OnClick({R2.id.lin_ask, R2.id.lin_paperTest, R2.id.lin_difficult
            , R2.id.lin_fun, R2.id.lin_situation, R2.id.lin_errorBook
            , R2.id.lin_search, R2.id.btn_paihang, R2.id.lin_more1, R2.id.lin_more2
    })
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.lin_ask) {
            goAskQuestion();
        } else if (i == R.id.lin_paperTest) {
            //试卷模拟
            ARouter.getInstance().build(ARouterPathUtils.App_NormalDetailWebActivity)
                    .withString("urlPath", dayiBean.getObj().getAnswer_examination_url())
                    .navigation();

        } else if (i == R.id.lin_difficult) {
            //难点刷题
            ARouter.getInstance().build(ARouterPathUtils.App_NormalDetailWebActivity)
                    .withString("urlPath", dayiBean.getObj().getAnswer_difficulty_url())
                    .navigation();
        } else if (i == R.id.lin_fun) {
            //趣味刷题
            ARouter.getInstance().build(ARouterPathUtils.App_NormalDetailWebActivity)
                    .withString("urlPath", dayiBean.getObj().getAnswer_interest_url())
                    .navigation();
        } else if (i == R.id.lin_situation) {
            //学情诊断
            ARouter.getInstance().build(ARouterPathUtils.App_NormalDetailWebActivity)
                    .withString("urlPath", dayiBean.getObj().getStudydiagnosis_content_url())
                    .navigation();

        } else if (i == R.id.lin_errorBook) {
            //错题本

            ARouter.getInstance().build(ARouterPathUtils.App_NormalDetailWebActivity)
                    .withString("urlPath", dayiBean.getObj().getNotebook_difficulty_url())
                    .navigation();
        } else if (i == R.id.lin_search) {

            sendMessageToUs();

            ARouter.getInstance().build(ARouterPathUtils.App_NormalDetailWebActivity)
                    .withString("urlPath", dayiBean.getObj().getArticle_search_url())
                    .navigation();
        } else if (i == R.id.btn_paihang) {
            ARouter.getInstance().build(ARouterPathUtils.App_NormalDetailWebActivity)
                    .withString("urlPath", dayiBean.getObj().getRanking_url())
                    .navigation();
        } else if (i == R.id.lin_more1) {
            ARouter.getInstance().build(ARouterPathUtils.App_NormalDetailWebActivity)
                    .withString("urlPath", dayiBean.getObj().getArticle_list_url())
                    .navigation();
        }
//        else if (i == R.id.lin_more2) {
//            ARouter.getInstance().build(ARouterPathUtils.App_NormalDetailWebActivity)
//                    .withString("urlPath", dayiBean.getObj().getOpen_course_list_url())
//                    .navigation();
//        }

    }


    private void sendMessageToUs() {

        String userPhone = "";
        String identity = "";

        if (!"".equals(SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserPhone())
                && null != SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserPhone()) {
            userPhone = SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserPhone();
            identity = SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserIdentity();
        }

        if (!"".equals(userPhone) && null != userPhone) {

            if ("1".equals(identity)) {
                identity = "老师";
            } else if ("2".equals(identity)) {
                identity = "学员";
            }

            String content = SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserName()
                    + "(" + SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserPhone() + ")"
                    + identity + "于" + TimeUtils.getNowString("yyyy-MM-dd HH:mm")
                    + "在Android App点击了搜索板块，请各位运营小伙伴跟进";

            LogUtil.e("用户进入搜索板块：" + content);

            HttpUtils.with(getActivity())
                    .addParam("requestType", "WX_PUSH")
                    .addParam("content", content)
                    .addParam("url_key", "0e21728f-a463-4d8f-9aed-983841207d3f")
                    .execute(new HttpNormalCallBack<SendMessageToUs>() {
                        @Override
                        public void onSuccess(SendMessageToUs result) {

                            if (CodeUtil.CODE_200 == result.getCode()) {

                                LogUtil.e("发送企业微信消息：" + result.getMsg());

                            }
                        }

                        @Override
                        public void onError(String e) {

                        }
                    });
        }

    }

    class TeacherListAdapter extends BaseAdapter<DayiBean.ObjBean.FamousTeacherListBean> {


        public TeacherListAdapter(Context context, List<DayiBean.ObjBean.FamousTeacherListBean> mData) {
            super(context, mData);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_teacher_list;
        }

        @Override
        protected void toBindViewHolder(ViewHolder holder, int position, List<DayiBean.ObjBean.FamousTeacherListBean> mData) {

            ImageView imageView = holder.getView(R.id.iv_usericon);
            Glide.with(getActivity())
                    .load(mData.get(position).getTeacher_icon())
                    .apply(GlideConfig.getRoundOptions(20))
                    .into(imageView);
        }
    }

}
